﻿using Domain.IRepositorys;
using Domain.Types;
using Domain.Utils;
using Infrastructure.AggregateBase;
using Infrastructure.Error;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;

namespace Domain.Services
{
    public class AdminService : IService
    {
        public IAdminRepository adminRepository { get; set; }
        public IRoleRepository roleRepository { get; set; }
        private IMemoryCache memoryCache { get; set; }

        public string Login(string name, string pwd)
        {
            if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(pwd))
            {
                throw new BizException("账号或密码不能为空");
            }
            var admin = adminRepository.Entities.FirstOrDefault(a => a.AdminName == name && a.AdminPass == pwd);
            if (admin == null)
            {
                throw new BizException("账号不存在或密码输入错误!");
            }
            if (admin.Status == (int)AdminStatus.冻结)
            {
                throw new BizException("账号已经被冻结");
            }

            Dictionary<string, object> payLoad = new Dictionary<string, object>();
            payLoad.Add("adminId", admin.ID);
            payLoad.Add("jti", Guid.NewGuid().ToString());
            payLoad.Add("name", admin.AdminName);
            payLoad.Add("time", DateTime.Now);
            payLoad.Add("expires", 60 * 60 * 24);
            var encodeJwt = JwtUtils.CreateToken(payLoad, 120);
            return encodeJwt;

        }
    }
}
